package com.duleme.servlet;

import com.duleme.common.DBUtils;
import com.duleme.common.EncodeUtils;
import com.duleme.common.JsonUtils;
import com.duleme.dao.ShoppingCartDao;
import com.duleme.entity.Delivery;
import com.duleme.entity.Order;
import com.duleme.entity.ShoppingCart;
import com.duleme.entity.User;
import com.duleme.service.CartService;
import com.duleme.service.ShopService;
import com.duleme.service.impl.CartServiceImpl;
import com.duleme.service.impl.ShopServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "TotalPriceServlet",urlPatterns = "/price/total")
public class TotalPriceServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EncodeUtils.setEncoding(request,response);
        User user = (User) request.getSession().getAttribute("user");
        /*User user = new User();
        user.setUserId(100020);*/
        new ShoppingCartDao().deleteAll();
        Delivery delivery = new Delivery();
        delivery.setDeliveryId(0);
        CartService cartService = new CartServiceImpl();
        ShoppingCart cart = cartService.getBookCart(user.getUserId());
        if (cart.getCount()==0){
            response.getWriter().write(1);
        }
        if (cartService.placeOrder(user.getUserId(),cart.getBooks(),delivery.getDeliveryId())){
            String json = JsonUtils.result2Json("1","total",String.valueOf(cart.getTotalPrice()));
            System.out.println(json);
            response.getWriter().write(json);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EncodeUtils.setEncoding(request,response);
        //User user = (User) request.getSession().getAttribute("user");
        double totalPrice = (double) request.getSession().getAttribute("totalPrice");
        String json = JsonUtils.result2Json("1","totalPrice",String.valueOf(totalPrice));
        response.getWriter().write(json);

    }
}
